<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of portfolioModelClass
 *
 * @author nstevens
 */
require_once 'mysql/dbHelper.php';
require_once 'classes/fiscalYear.php';
require_once 'model/commonModel.php';

class portfolioModelClass extends commonModel {

    public $string;
    //array
    public $fiscalYear; //contains all projects for one or more fiscal years

    public function __construct() {
        $this->fiscalYear = $this->getFiscalYearArray();
    }

    //HTML**********************************************************************

    function getPIApproverMainPage() {
        $output = "";
        $output .= $this->getPortfolioDetailsUpToMenu();
        //getStartOfOrderedList();
        //gets total funding and allocated funds for all fiscal years in the db 
        //$fundingResult = getAllocatedFundingData();
        //getFiscalYearFundingControlsDiv($fundingResult);
        //getProjectFundingControlsDiv(NULL);
        //getUpToMainMenu(getUserRole(), "PI Approver Main");
        //echo '<br><br>';
        //echo '<div class="topLeft">';
        //display Allocate Funding Level Form
        //getAllocateFundingLevelForm(getCurrentFY()+1);
        //Display current proposals
        //getProposedProjectsTable();
        // echo '</div>';
        //echo '<div class="topRight">';
        //Display current FY projects
        // getActiveProjectsTable(getCurrentFY());
        //echo '</div>';
        //Display current pi reviewed proposals
        //Option to start new FY funding control process
        //previous year projects - display total funding control dollars
        $output .= '<br><br> ' . getWebmasterFeedbackForm();
        $output .= getCloseTag("body");
        $output .= getCloseTag("html");
        return $output;
    }

    function getPortfolioDetailsUpToMenu() {
        $output = "";
        //get html up main menu
        $output .= getNewHtmlUpToMeta();
        $output .= getMantisCSSLine();
        $output .= getExpandOneCollapseOneScript();
        $output .= getConfirmBoxScript();
        $output .= getTitle("Portfolio Details");
        $output .= getCloseTag("head");
        $output .= getOpenTag("body");
        $output .= getLogoLine();
        $output .= getLoggedInAsLine();
        $output .= getMenuBar(getUserRole());
        $output .= '<br>';
        return $output;
    }

    function getFiscalYearFundingControlsDiv($fundingResult) {
        echo "<li><button value=\"press\" onclick=\"ToggleList('fyFundingControlsDiv')\" class=\"buttonExpandCollapse\">VIEW/ENTER/EDIT FISCAL YEAR FUNDING CONTROLS</button>";
        echo '<div class = "divInfo" id="fyFundingControlsDiv">';
        $allFundingHtmlText = getAllocateFundingLevelFormText(NULL, $fundingResult, NULL, true);
        echo $allFundingHtmlText;
        echo '</div></li>';
        echo '<br>';
    }

    function getProjectFundingControlsDiv() {
        echo "<li><button value=\"press\" onclick=\"ToggleList('projectFundingControlsDiv')\" class=\"buttonExpandCollapse\">VIEW/ENTER/EDIT PROJECT FUNDING CONTROLS</button>";
        echo '<div class = "divInfo" id="projectFundingControlsDiv">';
        getFiscalYearSubmitForm("portfolioController.php", "Select Project Fiscal Year", "Select Fiscal Year", NULL, true);
        //echo $allFundingHtmlText;
        echo '</div></li>';
        echo '<br>';
    }

    function getStartOfOrderedList() {
        echo '<ul id="ulist"><h1 class="centered"></h1>';
    }

    function getDisplayFundingAllocationsPage() {
        $output = $this->getBasicHeader("Funding Allocation");
        $output .= '<br><br>';
        if (isset($_GET['update'])) {
            $output .= $this->getFlagUnorderedList($_GET['update']);
        }
        $output .= '<div class="centerRounded">';
        $output .= $this->getAllocateFundingLevelFormText(NULL, NULL, true);
        $output .= '</div>';
        $output .= '<br><br> ' . getWebmasterFeedbackForm();
        $output .= '</body>';
        $output .= '</html>';
        return $output;
    }

    function getEditFundingAllocationsPage($fy) {
        $output = $this->getBasicHeader("Edit Allocation");
        $output .= '<br><br>';
        $output .= '<div class="centerRounded">';
        $output .= $this->getEditAllocateFundingLevelForm($this->getFiscalObject($fy));
        $output .= '</div>';
        $output .= '<br><br> ' . getWebmasterFeedbackForm();
        $output .= '</body>';
        $output .= '</html>';
        return $output;
    }

    function getPortfolioQuickSummary() {
        
    }

    function getApprovalProcessPage() {
        $decision = $_GET['approve'];
        if (isset($_GET['fy'])) {
            $fy = $_GET['fy'];
            $output = $this->getBasicHeader("Approve/Diapprove $fy Proposals");
        } else {
            $output = $this->getBasicHeader("Select Execution FY");
        }
        $output .= '<br><br>';

        //DISPLAY SELECT FY FORM****************************************************
        if (strcmp($decision, "1") === 0) {
            //select FY
            $output .= $this->getFiscalYearSubmitForm("mainPage.php?request=portfolio&action=fundAllocationSubmitRequest&approve=2", "Approve/Disapprove FY Proposals", "Select Fiscal Year");
        }
        //DISPLAY APPROVE/DISAPPROVE FORMS******************************************
        else {
            if (isset($_POST['fyDropdown'])) {
                $fy = $_POST['fyDropdown'];
            } else {
                $fy = $_GET['fy'];
            }
            if (isset($_GET['update'])) {
                $output .= $this->getFlagUnorderedList($_GET['update']);
            }
            //get total allocation table for the fy
            //getAllocateFundingSummaryForm($fy, NULL, "$fy Total Funding Allocated");
            $output .= $this->getAllocateFundingLevelFormText($this->getFiscalObject($fy), NULL, NULL, "$fy Total Funding Allocated");
            $output .= '<br><br>';
            //display summary form with a radio button approve/disapprove textfield for approval amount
            $output .= getFormLinePost("fundAllocationForm", "mainPage.php?request=portfolio&action=processDecisionSubmit");
            //getProposedProjectsTable($fy, true);
            $totalAllocatedFy = getFieldGivenAnID("fiscalyear", "year", $fy, "totalAllocated");
            $fiscalObj = $this->getFiscalObject($fy);
            if ($fy < getCurrentFY()) {
                $output .= $this->getProjectsShortSummaryTableText($fiscalObj, "$fy Projects", false, $totalAllocatedFy);
            } else {
                $output .= $this->getProjectsShortSummaryTableText($fiscalObj, "Current Proposals", true, $totalAllocatedFy);
            }
        }
        $output .= '<br><br> ' . getWebmasterFeedbackForm();
        return $output;
    }

    function getViewPortfolioPage() {
        $output = "";
        $output .= $this->getBasicHeader("Portfolio Summary");
        $output .= $this->getPortfolioSummaryTable();
        $output .= '<br><br> ' . getWebmasterFeedbackForm();
        $output .='</body></html>';
        return $output;
    }

    function getPortfolioSummaryTable($fy = NULL) {
        $output = "";
        if (!$fy) {
            $fy = getCurrentFY();
        }
        $fiscalObj = $this->getFiscalObject($fy);

        if ($fiscalObj && sizeof($fiscalObj->projects) > 0) {
            $output .= '<table class="width100" cellspacing="1">';
            $output .= ' <tr class="header">';
            $output .= $this->getTD('WBS');
            $output .= $this->getTD('Title');
            $output .= $this->getTD('Proposed $(K)');
            $output .= $this->getTD('Actual $(K)');
            $output .= $this->getTD('% Complete');
            $output .= $this->getTD('+/- $(K)');
            $output .= $this->getTD('+/- %');
            $output .= '</tr>';

            $counter = 0;
            foreach ($fiscalObj->projects as $project) {
                $output .= ' <tr class="field">';
                $output .= $this->getTD('<a class="black" href="mainPage.php?request=project&action=viewProjectDetails&projectId=' . $project->ID . '">' . $project->wbsString . '</a>');
                $output .= $this->getTD($project->title);
                $output .= $this->getTD($project->proposedCost);
                $output .= $this->getTD($project->actualCost);
                $output .= $this->getTD($project->getPercentComplete());
                $dollarDiff = $project->actualCost - $project->proposedCost;
                $output .= $this->getTD($dollarDiff);
                $percentDiff = round($dollarDiff / $project->proposedCost, 3) * 100;
                $output .= $this->getTD($percentDiff);
                $output .= '</tr>';
            }
            $output .= '</table>';
        } else {
            $output .= "<h2 class=\"centered\">There are no proposals for the selected year</h2>";
        }
        return $output;
    }

    /**
     * Returns the html test for a project long summary table (WBS, title, start, end, status, cost, Funding Org, Submit Date)
     * @param type $result the mysql result for the desired projets to display
     * @param type $title the caption for the table. If NULL caption = Projects
     * @param type $approve if true then displays the approve/disapprove information
     * @param type $totalAllocated total $$$ available for the fy
     * @return string
     */
    function getProjectsShortSummaryTableText($fiscalObj, $title = NULL, $approve = NULL, $totalAllocated = NULL) {
        $output = "";


        if ($fiscalObj && sizeof($fiscalObj->projects) > 0) {
            $totalAllocated = $fiscalObj->totalAllocated;
            $output .= '<table class="width100" cellspacing="1">';
            if ($approve) {
                $output .='<col width="4%"><col width="20%"><col width="8%"><col width="8%"><col width="8%"><col width="6%">
                       <col width="17%"><col width="10%"><col width="22%"><col width="5%">';
            }
            $output .= '<caption>' . $title . '</caption>';


            if ($approve) {
                $output .= projectModelClass::getShortSummaryHeaderWithApprovalColumns();
            } else {
                $output .= projectModelClass::getShortSummaryHeader();
            }

            $counter = 0;
            foreach ($fiscalObj->projects as $project) {
                $output .= ' <tr class="field">';
                $output .= ' <td>';
                $output .= '<a class="black" href="mainPage.php?request=project&action=viewProjectDetails&projectId=' . $project->ID . '">' . $project->wbsString . '</a>';
                $output .= ' </td>';
                $output .= ' <td>';
                $output .= $project->title;
                $output .= ' </td>';
                $output .= ' <td>';
                $output .= $project->fy;
                $output .= ' </td>';
                $output .= ' <td>';
                $output .= $project->proposedCost;
                $output .= ' </td>';

                if ($approve) {
                    $output .= ' <td>';
                    $output .= $project->approvedCost;
                    $output .= ' </td>';
                    $output .= ' <td>';
                    if ($totalAllocated == 0) {
                        $output .= "N/A";
                    } else {
                        $output .= round($project->approvedCost / $totalAllocated, 2) * 100;
                    }
                    $output .= ' </td>';
                    $output .= ' <td class="field2">';
                    $output .= getFormInputElementText('radio', "group$counter", "10%", "approve", NULL, "approveRadio", "checked");
                    $output .= "Approve<br>";
                    $output .= getFormInputElementText('radio', "group$counter", "10%", "disapprove", NULL, "approveRadio");
                    $output .= "Disapprove";
                    $output .= ' </td>';
                    $output .= ' <td class="field2">';
                    if ($project->approvedCost === 0) {
                        $output .= getFormInputElementText("text", "textFieldAmountApproved$counter", "96%", $project->proposedCost);
                    } else {
                        $output .= getFormInputElementText("text", "textFieldAmountApproved$counter", "96%", $project->approvedCost);
                    }
                    $output .= ' </td>';
                    $output .= ' <td class="field2">';
                    $output .= getFormInputElementText("text", "textFieldDisapproveComments$counter", "98%");
                    $output .= ' </td>';
                    $output .= ' <td class="field2">';
                    $output .= getHiddenFieldText("projectID$counter", $project->ID);
                    $output .= getFormInputElementText("submit", "submit$counter", NULL, "Submit Decision", "return myFunction(this.value)");
                    $output .= ' </td>';
                } else {
                    $output .= ' <td>';
                    $output .= 'spent';
                    $output .= ' </td>';
                }
                if (isset($fy)) {
                    $output .= getHiddenFieldText("fy", $fy);
                }
                $output .= ' </tr>';
                $counter++;
            }
            $output .= '</table>';
        } else {
            $output .= "<h2 class=\"centered\">There are no proposals for the selected year</h2>";
        }
        return $output;
    }

    function getEditExistingAllocationPage($fy) {
        $data = getFiscalYearData($fy);
        getNewHtmlUpToMeta();
        getJavascriptFileLine("js/formValidation.js");
        getMantisCSSLine();
        getTitle("Fund Allocation Edit");
        getCloseTag("head");
        getOpenTag("body");
        getLogoLine();
        getLoggedInAsLine();
        getMenuBar(getUserRole());
        echo '<br><br>';
        echo '<div class="topLeft">';
        echo getAllocateFundingLevelFormText(NULL, $data, "Edit");
        echo '</div>';
        echo '<div class="topRight">';
        echo '</div>';
        $output .= '<br><br> ' . getWebmasterFeedbackForm();
        echo '</body>';
        echo '</html>';
    }

    /**
     * Returns the string for an HTML form that contains elements to allocate funding 
     * controls for a Fiscal Year
     * @param type $fyObject if null displays all FY data in the list else only displays data from this object
     * @param type $typeRequest
     * @param type $showEmptyFY
     * @param type $caption
     * @return string
     */
    function getAllocateFundingLevelFormText($fyObject = NULL, $typeRequest = NULL, $showEmptyFY = NULL, $caption = NULL) {
        $output = "";
        //set variables    
        if (!$caption) {
            $caption = '<caption>Funding Allocation</caption>';
        } else {
            $caption = "<caption>$caption</caption>";
        }
        //form begin
        $output .= getFormLinePostWithOnSubmit("fundAllocationForm", "mainPage.php?request=portfolio&action=fundAllocationSubmitRequest", " validateFundAllocation(this)");
        //table begin
        $output .= '<table class="width100" cellspacing="1">';
        $output .= $caption;
        //header
        $output .= ' <tr class="header">';
        $output .= '<td>Fiscal Year</td><td>Total Funding</td><td>Amount Allocated</td><td>Difference</td><td></td>';
        $output .= '</tr>'; //end header
        //$year = $fy;
        $counter = 0;

        if ($fyObject) {
            $output .= '<tr class="field">';
            $output .= $this->getTD($fyObject->fy);
            $output .= $this->getTD($fyObject->totalFunding);
            $output .= $this->getTD($fyObject->totalAllocated);
            $output .= $this->getTD($fyObject->totalFunding - $fyObject->totalAllocated);
            $output .= $this->getTD("");
            $output .= '</tr>';
        } else {
            foreach ($this->fiscalYear as $curFiscalYear) {
                $year = $curFiscalYear->fy;
                $amountString = $curFiscalYear->totalFunding;
                $amountAllocated = $curFiscalYear->totalAllocated;

                $output .= '<tr class="field">';
                if (strcmp($typeRequest, "Edit") === 0) {
                    $submitString = getFormInputElementText('submit', "submit", "98%", "Save Changes");
                    $amountString = getFormInputElementText("text", "amountTextField", "98%", $amountString);
                    $output .= '<td>' . $year . ' ' . getHiddenFieldText("fy", $year) . '</td>';
                    $output .= '<td>' . $amountString . '</td>';
                } else {
                    $submitString = getFormInputElementText('submit', "submit$counter", "98%", "Edit");
                    $output .= '<td>' . $year . ' ' . getHiddenFieldText("fy$counter", $year) . '</td>';
                    $output .= '<td>' . $amountString . ' ' . getHiddenFieldText("amountTextField$counter", $amountString) . '</td>';
                }

                $output .= '<td>' . $amountAllocated . '</td>';
                $output .= '<td>' . ($amountString - $amountAllocated) . '</td>';
                //$output .= getHiddenFieldText("amountTextField", $amountString);
                $output .= '<td>' . $submitString . '</td>';
                $output .= '</tr>'; //end fields
                $year++;
                $counter++;
            }
        }
        if (strcmp($typeRequest, "Edit") !== 0) {
            if ($showEmptyFY) {
                $output .= '<tr class="field">';
                $amountString = getFormInputElementText("text", "amountTextField", "98%");
                $submitString = getFormInputElementText('submit', 'submit', "98%", "Save Allocation");
//            if(!$year){
//                $year = getCurrentFY();
//            }
                $output .= '<td>' . $year . ' ' . getHiddenFieldText("fy", $year) . '</td>';
                $output .= '<td>' . $amountString . '</td>';
                $output .= '<td>N/A</td><td>N/A</td>';
                $output .= '<td>' . $submitString . '</td>';
                $output .= '</tr>'; //end fields
            }
        }
        $output .= '</table>'; //end table
        $output .= '</form>'; //end form
        return $output;
    }

    function getEditAllocateFundingLevelForm($fiscalYearObj) {
        $output = "";
        //set variables
        $caption = '<caption>Funding Allocation</caption>';
        //form begin
        $output .= getFormLinePostWithOnSubmit("fundAllocationForm", "mainPage.php?request=portfolio&action=fundAllocationSubmitRequest", " validateFundAllocation(this)");
        //table begin
        $output .= '<table class="width100" cellspacing="1">';
        $output .= $caption;
        //header
        $output .= ' <tr class="header">';
        $output .= '<td>Fiscal Year</td><td>Total Funding</td><td></td>';
        $output .= '</tr>'; //end header
        $output .= '<tr class="field">';
        $output .= '<td>' . $fiscalYearObj->fy;
        $output .= getHiddenField('fy', $fiscalYearObj->fy) . '</td>';
        $output .= '<td>' . getFormInputElement('text', "amountTextField", "97%", $fiscalYearObj->totalFunding) . '</td>';
        $output .= $this->getTD(getFormInputElementText('submit', 'submit', "98%", "Save Allocation"));
        $output .= '</tr>'; //end fields
        $output .= '</table>'; //end table
        $output .= '</form>'; //end form
        return $output;
    }

    //DATA FILL*****************************************************************
    function getFiscalYearArray() {
        $array = array();
        $fyResult = executeSelect("SELECT DISTINCT fy FROM project ORDER BY fy");
        while ($row = mysqli_fetch_array($fyResult)) {
            $fy = $row['fy'];
            $fyObj = new fiscalYear($fy);
            array_push($array, $fyObj);
        }
        return $array;
    }

    public function getFiscalObject($fy) {
        if (!$this->fiscalYear) {
            $this->fiscalYear = getFiscalYearArray();
        }
        foreach ($this->fiscalYear as $curFiscalYear) {
            if (strcmp($fy, $curFiscalYear->fy) === 0) {
                return $curFiscalYear;
            }
        }
        return NULL;
    }

    function isFYFundingLevelSet($fy) {
        $result = executeSelect("SELECT * FROM fiscalyear WHERE year=$fy");
        if ($result && $result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    function getFiscalYearData($fy) {
        return executeSelect("SELECT * FROM fiscalyear WHERE year=$fy");
    }

    //PROCESS SUBMISSION********************************************************
    /**
     * Sets allocation $$$ for a fiscal year
     * @return string|null
     */
    function processSaveAllocationRequest() {
        $fy = $_POST['fy'];
        $amount = $_POST['amountTextField'];
        $exists = executeSelect("SELECT * FROM fiscalyear WHERE year=$fy");
        if ($exists && $exists->num_rows > 0) {
            $insertResult = executeUpdate("UPDATE fiscalyear set totalFunding=$amount WHERE year=$fy");
        } else {
            $insertResult = executeUpdate("INSERT into fiscalyear (year, totalFunding) values ($fy, $amount)");
        }
        if ($insertResult) {
            return "location:mainPage.php?request=portfolio&action=viewFundingAllocationRequest&update=Allocation Successfully Saved (allocation may not display if 0 projects are linked to that fy - Fix In Progress)";
        } else {
            return NULL;
        }
    }

    /**
     * Updates allocation $$$ for a fiscal year
     * @return string|null
     */
    function processEditAllocationRequest($index) {
        $amount = $_POST["amountTextField$index"];
        $fy = $_POST["fy$index"];
        $insertResult = executeUpdate("UPDATE fiscalyear SET totalFunding=$amount WHERE year=$fy");
        if ($insertResult) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Processed an approval/disapproval for a proposal and sets the approval amount if applicable
     * @return boolean
     */
    function processApprovalDecisionRequest() {
        //print_r($_POST);
        //return;
        //process Submit Decision
        $index = getIndexClickedGenericList('submit', 20);
        $projectId = $_POST["projectID$index"];
        $decision = $_POST["group$index"];
        $approvedCost = $_POST["textFieldAmountApproved$index"];
        //$comments = $array["comments"];
        $fy = getFieldGivenAnID('project', 'projectID', $projectId, "fy");
        //echo $decision;
        if (strcmp($decision, "approve") === 0) {
            $result = executeUpdate("UPDATE project SET approvedCost=$approvedCost, status='approved' WHERE projectID=$projectId");
            //echo "UPDATE project SET approvedCost=$approvedCost, status='approved' WHERE projectID=$projectId";
            //echo 'Updated approve<br>';
        } else {
            //disapproved
            $result = executeUpdate("UPDATE project SET approvedCost=0, status='disapproved' WHERE projectID=$projectId");
            //echo 'Updated disapprove<br>';
        }
        if ($result) {
            //echo 'Updated success<br>';
            if (updateFiscalYearAllocated($fy)) {
                //echo 'Updated fy allocated success<br>';
                return 'location:mainPage.php?request=portfolio&action=getProcessApprovalPage&approve=2&fy=' . $fy . '&update=Decision Processed Successfully';
                //return NULL;
            }
            return NULL;
        }
    }

}

?>
